#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
闲云潭影日悠悠, 物转星移几度秋!
						--王勃
"""
from pyse import Pyse
from time import sleep

CSS_SUBMIT = "id=>J_SubmitQuick"
CSS_USER_FORMAT = "css=>#J_QuickLogin > form > ul.userlist > li:nth-child(%s) > label"
URL='https://login.taobao.com/member/login.jhtml?style=mini&from=alimama'
TITLE = u'阿里妈妈 大数据营销平台'


def getAlimamaCookies(user, manual=False):
	"""

	自动登录阿里妈妈获取cookie, 前提是旺旺在线
	"""
	driver = Pyse("ie")
	driver.open(URL)
	driver.element_wait("css", ".userlist", 5)

	cookies = None
	if manual:
		cookies = manualLogin(driver, user)
	else:
		cookies = autoChoiceUserLogin(driver, user)
	try:
		driver.close()
	except:
		pass
	return cookies

def manualLogin(driver, user):
	"""

	手动登录
	"""
	cookies = None

	tryTimes = 10
	while tryTimes > 0:
		sleep(1)
		string = '手动选择用户登录: %s' % (user.encode('utf-8'))
		print unicode(string, 'utf-8').encode('gbk')
		try:
			if driver.title_contains(TITLE, 10):
				cookies = driver.get_cookies()
				print unicode('登录成功', 'utf-8').encode('gbk')
				break
		except:
			pass
		tryTimes -= 1
	return cookies

def autoChoiceUserLogin(driver, user):
	"""

	自动登录
	"""
	cookies = None

	n = 1
	while n < 3:
		print n
		try:
			text = driver.get_text(CSS_USER_FORMAT % n)
			if text == user:
				driver.click( CSS_USER_FORMAT % n )
				sleep(0.5)
				driver.submit(CSS_SUBMIT)
				sleep(0.5)
				if driver.title_contains(TITLE, 10):
					cookies = driver.get_cookies()
				else:
					driver.F5()
					driver.click( CSS_USER_FORMAT % n )
					driver.submit(CSS_SUBMIT)
					driver.title_contains(TITLE, 10)
					cookies = driver.get_cookies()
				break
		except Exception as e:
			pass
		n += 1
	return cookies


def example():
	"""
	
	例子
	"""
	user = u'旺旺用户名'
	print getAlimamaCookies(user)

if __name__ == '__main__':
	example()